package cn.bitkit.component.aop;

import cn.bitkit.base.annotation.Lock;
import cn.bitkit.component.common.SpelHandler;
import cn.bitkit.component.context.SpringContext;
import cn.bitkit.component.id.IdHelper;
import cn.bitkit.component.redis.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.StringRedisTemplate;

@Slf4j
@Aspect
public class LockHandler {

    @Around(value = "@annotation(lockTag)")
    public Object doLock(ProceedingJoinPoint joinPoint, Lock lockTag) {
        StringRedisTemplate stringRedisTemplate = SpringContext.getAssertedBean(StringRedisTemplate.class);
        String lockKey = SpelHandler.getString(joinPoint, lockTag.lockKey());
        String lockValue = IdHelper.getId();
        boolean lock = RedisLock.tryLock(lockKey, lockValue, lockTag.expire()*1000L);
        if(!lock){
            return null;
        }
        try {
            return joinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            RedisLock.release(lockKey, lockValue);
        }
    }

}
